package com.wenfs.demo.controller;

import com.wenfs.demo.entity.MyException;
import com.wenfs.demo.entity.Result;
import com.wenfs.demo.util.result.ResultHandler;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 统一异常处理类
 * @author wenfs
 */
@ControllerAdvice
public class MyExceptionController {
  @ExceptionHandler(value = Exception.class)
  @ResponseBody
  public Result handler(Exception e) throws Exception {
    System.out.println(ExceptionUtils.getStackTrace(e));
    if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
      throw e;
    }
    if (e instanceof MyException) {
      MyException exception = (MyException) e;
      return ResultHandler.error(exception.getErrorCode(), exception.getMessage());
    }
    return ResultHandler.error("-1", "服务器出错：" + e.getMessage());
  }


}
